import { sync } from 'cross-spawn';
import fs from 'fs-extra';
import path from 'path';

function initProjectPath(name: string) {
  const cwd = path.join(process.cwd(), name);
  if (fs.existsSync(cwd)) {
    sync(`rm`, ['-rf', name], { cwd: process.cwd(), stdio: 'inherit' });
  }
  //todo: 询问是否删除
  const result = sync('mkdir', [name], {
    cwd: process.cwd(),
    stdio: 'inherit',
  });
  return result;
}

function initUmi(name: string) {
  initProjectPath(name);
  sync('yarn', ['create', 'umi'], {
    cwd: path.join(process.cwd(), name),
    stdio: 'inherit',
  });
}

function initVite(name: string, isAnt = false) {
  sync('yarn', ['create', 'vite', name, '--template', 'react'], {
    cwd: process.cwd(),
    stdio: 'inherit',
  });
  if (isAnt) {
    sync('yarn', ['add', 'antd'], {
      cwd: path.join(process.cwd(), name),
      stdio: 'inherit',
    });
  }
}

const handles: any = { umi: initUmi, viteAntd: initVite, initVite: 'vite' };

export default (options: any) => {
  let name = '';

  if (typeof options === 'string') {
    name = options;
    initVite(name);
  } else {
    const keys = Object.keys(options || {});
    keys?.forEach((key: any) => {
      const handle = handles?.[key];
      handle?.(options?.[key], true);
    });
  }
};
